package cn.itcast.web.action;

import cn.itcast.domain.base.Standard;
import cn.itcast.service.StandardService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.convention.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
@Actions
public class StandardAction extends ActionSupport implements ModelDriven<Standard> {
    @Autowired
    private StandardService standardService;
    private Standard standard=new Standard();

    @Override
    public Standard getModel() {
        return standard;
    }

    //保存订单信息
    @Action(value = "standard_save",results={@Result(name="success",location = "./pages/base/standard.html",type = "redirect")})
    public String save(){
        standardService.save(standard);

        return SUCCESS;
    }
    //分页查询
       //接受参数
    private Integer page;//当前页
    private Integer rows;//每页记录

    public void setPage(Integer page) {
        this.page = page;
    }

    public void setRows(Integer rows) {
        this.rows = rows;
    }
    @Action(value="standard_pageQuery",results={@Result(name="success",type = "json")})
    public String pageQuery(){
        //底层可以做到根据pageable对象进行分页查询 创建pageable对象
        Pageable pageable=new PageRequest(page-1,rows);//底层的当前页面时从0开始计数
        Page<Standard>pageData= standardService.findPageDate(pageable);
        //json返回格式属性要求 total rows 使用map进行属性包装再返回
        Map<String,Object> result=new HashMap<>();
        result.put("total",pageData.getTotalElements());//TotalElements 是总记录数
        result.put("rows",pageData.getContent());//content被封装在list集合中的对象
        //将map压在栈顶 valuestack自动将栈顶数据作为json格式返回
        ActionContext.getContext().getValueStack().push(result);

        return SUCCESS;
    }
     @Action(value="standard_findAll",results={@Result(name="success",type = "json")})
    public String findAll(){
         List<Standard>standards=standardService.findAll();
         ActionContext.getContext().getValueStack().push(standards);
        return SUCCESS;
    }


}
